package com.hotel.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotel.common.Result;
import com.hotel.entity.MarketingActivity;
import com.hotel.service.MarketingActivityService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 营销活动管理控制器
 *
 * @author Hotel Management Team
 */
@RestController
@RequestMapping("/marketing-activity")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class MarketingActivityController {

    private final MarketingActivityService marketingActivityService;

    /**
     * 分页查询营销活动
     */
    @GetMapping("/list")
    public Result<Page<MarketingActivity>> getActivityPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {

        // 构建查询条件
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MarketingActivity> queryWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();

        if (keyword != null && !keyword.trim().isEmpty()) {
            queryWrapper.like("activity_name", keyword)
                    .or()
                    .like("description", keyword);
        }

        if (status != null && !status.trim().isEmpty()) {
            queryWrapper.eq("status", status);
        }

        if (type != null && !type.trim().isEmpty()) {
            queryWrapper.eq("activity_type", type);
        }

        queryWrapper.orderByDesc("create_time");

        Page<MarketingActivity> page = new Page<>(current, size);
        Page<MarketingActivity> result = marketingActivityService.page(page, queryWrapper);

        return Result.success(result);
    }

    /**
     * 获取营销活动详情
     */
    @GetMapping("/{id}")
    public Result<MarketingActivity> getActivityById(@PathVariable Long id) {
        MarketingActivity activity = marketingActivityService.getById(id);
        if (activity != null) {
            return Result.success(activity);
        } else {
            return Result.error("营销活动不存在");
        }
    }

    /**
     * 创建营销活动
     */
    @PostMapping
    public Result<Void> createActivity(@Valid @RequestBody MarketingActivity activity) {
        // 设置默认状态
        if (activity.getStatus() == null) {
            activity.setStatus(1);
        }

        boolean success = marketingActivityService.save(activity);
        if (success) {
            return Result.success("营销活动创建成功");
        } else {
            return Result.error("营销活动创建失败");
        }
    }

    /**
     * 更新营销活动
     */
    @PutMapping("/{id}")
    public Result<Void> updateActivity(@PathVariable Long id, @Valid @RequestBody MarketingActivity activity) {
        activity.setId(id);
        boolean success = marketingActivityService.updateById(activity);
        if (success) {
            return Result.success("营销活动更新成功");
        } else {
            return Result.error("营销活动更新失败");
        }
    }

    /**
     * 删除营销活动
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteActivity(@PathVariable Long id) {
        boolean success = marketingActivityService.removeById(id);
        if (success) {
            return Result.success("营销活动删除成功");
        } else {
            return Result.error("营销活动删除失败");
        }
    }

    /**
     * 启动营销活动
     */
    @PutMapping("/{id}/start")
    public Result<Void> startActivity(@PathVariable Long id) {
        MarketingActivity activity = marketingActivityService.getById(id);
        if (activity == null) {
            return Result.error("营销活动不存在");
        }
// 获取当前日期时间的日期部分进行比较
        LocalDate today = LocalDate.now();

        if (activity.getStartDate() != null && activity.getStartDate().isAfter(today)) {
            return Result.error("活动还未到开始时间");
        }

        if (activity.getEndDate() != null && activity.getEndDate().isBefore(today)) {
            return Result.error("活动已过期");
        }


        activity.setStatus(1);
        boolean success = marketingActivityService.updateById(activity);
        if (success) {
            return Result.success("营销活动启动成功");
        } else {
            return Result.error("营销活动启动失败");
        }
    }

    /**
     * 暂停营销活动
     */
    @PutMapping("/{id}/pause")
    public Result<Void> pauseActivity(@PathVariable Long id) {
        MarketingActivity activity = marketingActivityService.getById(id);
        if (activity == null) {
            return Result.error("营销活动不存在");
        }

        activity.setStatus(0);
        boolean success = marketingActivityService.updateById(activity);
        if (success) {
            return Result.success("营销活动暂停成功");
        } else {
            return Result.error("营销活动暂停失败");
        }
    }

    /**
     * 结束营销活动
     */
    @PutMapping("/{id}/end")
    public Result<Void> endActivity(@PathVariable Long id) {
        MarketingActivity activity = marketingActivityService.getById(id);
        if (activity == null) {
            return Result.error("营销活动不存在");
        }

        activity.setStatus(0);
        boolean success = marketingActivityService.updateById(activity);
        if (success) {
            return Result.success("营销活动结束成功");
        } else {
            return Result.error("营销活动结束失败");
        }
    }

    /**
     * 获取进行中的营销活动
     */
    @GetMapping("/active")
    public Result<List<MarketingActivity>> getActiveActivities() {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MarketingActivity> queryWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("status", "active")
                .le("start_time", LocalDateTime.now())
                .ge("end_time", LocalDateTime.now())
                .orderByDesc("create_time");

        List<MarketingActivity> activities = marketingActivityService.list(queryWrapper);
        return Result.success(activities);
    }

    /**
     * 获取即将开始的营销活动
     */
    @GetMapping("/upcoming")
    public Result<List<MarketingActivity>> getUpcomingActivities() {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MarketingActivity> queryWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("status", "active")
                .gt("start_time", LocalDateTime.now())
                .orderByAsc("start_time");

        List<MarketingActivity> activities = marketingActivityService.list(queryWrapper);
        return Result.success(activities);
    }

    /**
     * 获取已结束的营销活动
     */
    @GetMapping("/ended")
    public Result<List<MarketingActivity>> getEndedActivities() {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MarketingActivity> queryWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("status", "ended")
                .or()
                .lt("end_time", LocalDateTime.now())
                .orderByDesc("end_time");

        List<MarketingActivity> activities = marketingActivityService.list(queryWrapper);
        return Result.success(activities);
    }

    /**
     * 根据类型获取营销活动
     */
    @GetMapping("/type/{type}")
    public Result<List<MarketingActivity>> getActivitiesByType(@PathVariable String type) {
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MarketingActivity> queryWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        queryWrapper.eq("activity_type", type)
                .orderByDesc("create_time");

        List<MarketingActivity> activities = marketingActivityService.list(queryWrapper);
        return Result.success(activities);
    }

    /**
     * 获取营销活动统计信息
     */
    @GetMapping("/stats")
    public Result<java.util.Map<String, Object>> getActivityStats() {
        java.util.Map<String, Object> stats = new java.util.HashMap<>();

        // 总活动数
        long totalActivities = marketingActivityService.count();
        stats.put("totalActivities", totalActivities);

        // 进行中的活动数
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MarketingActivity> activeWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        activeWrapper.eq("status", "active")
                .le("start_time", LocalDateTime.now())
                .ge("end_time", LocalDateTime.now());
        long activeActivities = marketingActivityService.count(activeWrapper);
        stats.put("activeActivities", activeActivities);

        // 草稿状态活动数
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MarketingActivity> draftWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        draftWrapper.eq("status", "draft");
        long draftActivities = marketingActivityService.count(draftWrapper);
        stats.put("draftActivities", draftActivities);

        // 已结束活动数
        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<MarketingActivity> endedWrapper =
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
        endedWrapper.eq("status", "ended")
                .or()
                .lt("end_time", LocalDateTime.now());
        long endedActivities = marketingActivityService.count(endedWrapper);
        stats.put("endedActivities", endedActivities);

        return Result.success(stats);
    }

    /**
     * 批量更新活动状态
     */
    @PutMapping("/batch-status")
    public Result<Void> batchUpdateStatus(
            @RequestParam List<Long> ids,
            @RequestParam Integer status) {

        for (Long id : ids) {
            MarketingActivity activity = marketingActivityService.getById(id);
            if (activity != null) {
                activity.setStatus(status);
                marketingActivityService.updateById(activity);
            }
        }

        return Result.success("批量更新状态成功");
    }
}